package com.cardone.platform.configuration.action;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import com.cardone.context.ContextHolder;
import com.cardone.context.action.Run3Action;
import com.cardone.platform.configuration.dto.DictionaryDto;
import com.cardone.platform.configuration.service.DictionaryService;

/**
 * bean属性名称支持
 *
 * @author fand.cardone
 *
 */
public class CopyPropertiesMap2MapForDictionaryAction implements Run3Action<Object, Object, Map<String, Object>> {
	@Override
	public void run(final Object source, final Object target, final Map<String, Object> parameters) {
		@SuppressWarnings("unchecked")
		final Map<String, Object> sourceMap = (Map<String, Object>) source;

		@SuppressWarnings("unchecked")
		final Map<String, Object> targetMap = (Map<String, Object>) target;

		for (final Entry<String, Object> parameterEntry : parameters.entrySet()) {
			final Object objectDictionaryId = MapUtils.getObject(sourceMap, parameterEntry.getKey());

			String dictionaryId = null;

			if (objectDictionaryId instanceof String) {
				dictionaryId = (String) objectDictionaryId;
			}

			String targetName = null;

			if (parameterEntry.getValue() instanceof String) {
				targetName = (String) parameterEntry.getValue();
			}

			if (StringUtils.isBlank(targetName)) {
				targetName = parameterEntry.getKey();
			}

			if (StringUtils.isBlank(dictionaryId)) {
				targetMap.put(targetName, null);

				continue;
			}

			final DictionaryDto findDictionary = DictionaryDto.newDictionary();

			findDictionary.setId(dictionaryId);

			final DictionaryDto dictionary = ContextHolder.getBean(DictionaryService.class).findById(DictionaryDto.class, findDictionary);

			if (dictionary == null) {
				targetMap.put(targetName, null);

				continue;
			}

			targetMap.put(targetName, dictionary.getName());
		}
	}
}